package bot.controller;

import bot.conf.WYYMusicURL;
import bot.pojo.WyyReturn;
import bot.pojo.returns;
import bot.pojo.songs;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
//@Api(description = "网易云api")
@RestController
@RequestMapping("/music")
public class MusicController {
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    //@ApiOperation("查歌")
    @GetMapping("/getmusic")
    public Object getmusic(String name) throws UnsupportedEncodingException {
        name = URLEncoder.encode(name, "utf-8");
        String s1 = HttpHelp.sendGet(WYYMusicURL.URL+"/search?keywords="+name+"&limit=10");
        returns wyyReturn = JSONObject.parseObject(s1, returns.class);
        if (wyyReturn.getResult()==null){
            return null;
        }
        List<songs> songs = wyyReturn.getResult().getSongs();

        for(int i =0 ; i<songs.size() ; i++){
            if(songs.get(i).getAlias().size() == 0 ){
                songs.get(i).getAlias().add("无");
            }
            /**
             * 2025/2/5： 去掉redis缓存
             * */
            //redisTemplate.opsForValue().set(songs.get(i).getId() , songs.get(i));
            //给redis设置毫秒值
            //第一个参数是key
            //第二个参数是值
            //第三个参数是时间颗粒度转换,一天后缓存失效
            //redisTemplate.expire(songs.get(i).getId(),2, TimeUnit.HOURS);
        }
        return  wyyReturn;
    }
    @GetMapping("/sendmusic")
    public Object sendmusic(Integer id){
        String s1 = HttpHelp.sendGet(WYYMusicURL.URL+"/song/url?id="+id);
        JSONObject jsonObject = JSONObject.parseObject(s1);
        String MusicURL =  jsonObject.getJSONArray("data").getJSONObject(0).get("url").toString();


        returns songs = JSONObject.parseObject(s1, returns.class);
        if (songs == null){
            return null;
        }
        String s = JSONObject.toJSONString(songs);
        return s;
    }
    public String delRdis(){
        Set<Object> keys = redisTemplate.keys("*");
        redisTemplate.delete(keys);

        return "true";
    }

}
